import 'package:common_utils/common_utils.dart';
import 'package:flutter/material.dart';

import 'calendar_bottom_sheet.dart';

class CalendarButton extends StatefulWidget {
  final Function(dynamic data) clickBack;

  final double fFramHeight; //边框H
  final String defaultDate;
  //final String tet = DateUtil.formatDate(DateTime.now(), format: 'yyyy-MM-dd');
  final bool bIsReSet;

  const CalendarButton({
    Key? key,
    required this.clickBack,
    this.fFramHeight = 50,
    this.defaultDate = "",
    this.bIsReSet = false,
  }) : super(key: key);

  @override
  // ignore: library_private_types_in_public_api
  _CalendarButtonState createState() => _CalendarButtonState();
}

class _CalendarButtonState extends State<CalendarButton> {
  late String selectStr;

  @override
  void initState() {
    super.initState();
    _initData();
  }

  void _initData() {
    if (widget.defaultDate.isEmpty) {
      selectStr = DateUtil.formatDate(DateTime.now(), format: 'yyyy-MM-dd');
    } else {
      selectStr = widget.defaultDate;
    }
  }

  @override
  void didUpdateWidget(CalendarButton oldWidget) {
    super.didUpdateWidget(oldWidget);

    //重置
    if (widget.bIsReSet) {
      _initData();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      heightFactor: 1.0,
      child: Container(
        height: widget.fFramHeight,
        decoration: BoxDecoration(
          borderRadius: const BorderRadius.all(Radius.circular(6)),
          border: Border.all(width: 1, color: Colors.grey),
        ),
        child: InkWell(
          // splashColor: Colors.transparent,
          // highlightColor: Colors.transparent,
          onTap: () {
            onPressCalendar();
          },
          child: Row(
            mainAxisSize: MainAxisSize.max,
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              const SizedBox(
                width: 12,
              ),
              Text(
                selectStr,
                style: const TextStyle(fontSize: 16, color: Colors.black),
              ),
              const Spacer(),
              const Icon(Icons.calendar_month, size: 20, color: Colors.blue),
              const SizedBox(
                width: 12,
              ),
            ],
          ),
        ),
      ),
    );
  }

  void onPressCalendar() {
    DateTime tTime = DateTime.now();
    if (selectStr.isNotEmpty) {
      tTime = DateTime.parse(selectStr);
    }

    print(selectStr);
    CalendarBottomSheet.showBottomCalendar(context, tDefDateTime: tTime,
        clickCallback: (dynamic data) {
      print("选择的日期 : $data");
      DateTime tSelData = data;
      String strStartTime = DateUtil.formatDate(tSelData, format: 'yyyy-MM-dd');
      //print(strStartTime);
      widget.clickBack(strStartTime);
      setState(() {
        selectStr = strStartTime;
      });
    });
  }
}
